package com.windoent.yugioh.ui.activity.setting;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.baidu.mobstat.StatService;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.windoent.yugioh.R;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.UserInfoBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.utils.XingUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.Map;

import okhttp3.Call;

import static com.windoent.yugioh.constants.Constants.APP_ID;

/**
 * author : robert
 * date   : 2021/5/12 15:29
 * desc   :账户安全
 */
public class SettingSafeAccountActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private TextView mTvPhoneNumber;
    private TextView mTvChangePhone;
    private TextView mTvEmailNumber;
    private TextView mTvChangeEmail;
    private Switch mSwitchWechatButton;
    private Switch mSwitchQqButton;
    private String phone;
    private MessageReceiver messageReceiver;

    @Override
    public int getLayout() {
        return R.layout.activity_setting_safe_account;
    }

    @Override
    public void initView() {
        super.initView();
        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mTvPhoneNumber = (TextView) findViewById(R.id.tv_phone_number);
        mTvChangePhone = (TextView) findViewById(R.id.tv_change_phone);
        mTvEmailNumber = (TextView) findViewById(R.id.tv_email_number);
        mTvChangeEmail = (TextView) findViewById(R.id.tv_change_email);
        mSwitchWechatButton = (Switch) findViewById(R.id.switch_wechat_button);
        mSwitchQqButton = (Switch) findViewById(R.id.switch_qq_button);
    }

    @Override
    public void initData() {
        super.initData();
        defaultSwitchBtn(false, false);
        regToWx();
        registerAliasReceiver();
        getUserInfo();
    }

    //初始默认值
    private void getUserInfo() {
        showLoadingDialog("");
        PhoneLive.getUserInfoByToken(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(response)) {
                            UserInfoBean bean = gson.fromJson(response, UserInfoBean.class);
                            if (bean != null) {
                                UserInfoBean.DataBean data = bean.getData();
                                if (data != null) {
                                    UserInfoBean.DataBean.UserBean user = data.getUser();
                                    if (user != null) {
                                        UserInfoBean.DataBean.UserBean.PlatformBean platform = user.getPlatform();
                                        boolean isQQ = platform.isQq();
                                        boolean isWx = platform.isWx();
                                        defaultSwitchBtn(isQQ, isWx);
                                    }
                                    phone = user.getPhone();
                                    String email = user.getEmail();
                                    setText(mTvPhoneNumber, XingUtils.xingPhone(phone));
                                    setText(mTvEmailNumber, XingUtils.xingEmail(email));
                                    mTvChangeEmail.setText(BaseMethod.notNull(email) ? getString(R.string.sting_change_email_numbers) : getString(R.string.string_bind_email));
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //获取登陆成功用户id
    private void registerAliasReceiver() {
        messageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Constants.MESSAGE_RECEIVED_ALIAS_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, filter);
    }


    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (Constants.MESSAGE_RECEIVED_ALIAS_ACTION.equals(intent.getAction())) {
                    String code = intent.getStringExtra(Constants.WEIXINCODE);
                    LogUtils.d("得到的code：" + code);
                    bindWX(code);
                } else wxSwitchCheck(false);
            } catch (Exception e) {
                wxSwitchCheck(false);
                e.printStackTrace();
            }
        }
    }

    //绑定wx
    private void bindWX(String code) {
        showLoadingDialog("");
        PhoneLive.bindWX(getUserToken(), code, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                wxSwitchCheck(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean json = gson.fromJson(response, GeneralBean.class);
                            if (json != null) {
                                ToastUtils.showText(BaseMethod.notNullDefaultValue(json.getMsg(), getString(R.string.string_bind_third_sucess_warn)));
                                wxSwitchCheck(true);
                            } else wxSwitchCheck(false);
                        } else wxSwitchCheck(false);
                    } catch (JSONException e) {
                        wxSwitchCheck(false);
                        e.printStackTrace();
                    }
                } else {
                    wxSwitchCheck(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, false);

        // 将应用的appId注册到微信
        api.registerApp(APP_ID);

    }

    //第三方登录状态
    private void defaultSwitchBtn(boolean isQq, boolean isWx) {
        mSwitchQqButton.setChecked(isQq);
        mSwitchWechatButton.setChecked(isWx);
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTvChangePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //修改手机号
                Intent intent = new Intent(mContext, SettingChangePhoneActivity.class);
                startActivity(intent);
            }
        });
        mTvChangeEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseMethod.notNull(phone)) {
                    getCellPhoneCode(phone);
                } else {
                    ToastUtils.showText(getString(R.string.string_phone_null));
                }
            }
        });
        mSwitchWechatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isChecked = mSwitchWechatButton.isChecked();
                if (!isChecked) {
                    //解绑wx
                    unbind("wx");
                } else {
                    //绑定微信
                    bindWx();
                }
            }
        });
        mSwitchQqButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isChecked = mSwitchQqButton.isChecked();
                if (!isChecked) {
                    //解绑QQ
                    unbind("qq");
                } else {
                    //绑定QQ
                    bindQq();
                }
            }
        });
    }

    private void qqSwitchCheck(boolean checked) {
        mSwitchQqButton.setChecked(checked);
    }

    private void wxSwitchCheck(boolean checked) {
        mSwitchWechatButton.setChecked(checked);
    }

    //绑定QQ
    private void bindQq() {
        //QQ
        UMShareAPI.get(mContext).getPlatformInfo(SettingSafeAccountActivity.this, SHARE_MEDIA.QQ, authListener);
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoadingDialog(getString(R.string.string_qq_authing));
            qqSwitchCheck(false);
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_souquan_qq_sucess));
            LogUtils.d("zkk-->" + data.toString());
            if (data != null) {
                bindQQ(data);
            } else qqSwitchCheck(false);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_auth_defeat) + t.getMessage());
            qqSwitchCheck(false);
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_auth_cancel));
            qqSwitchCheck(false);
        }
    };

    //绑定qq
    private void bindQQ(Map<String, String> data) {
        showLoadingDialog("");
        final String access_token = data.get("access_token");
        final String openid = data.get("openid");
        PhoneLive.bindQQ(getUserToken(), openid, access_token, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                qqSwitchCheck(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean json = gson.fromJson(response, GeneralBean.class);
                            if (json != null) {
                                ToastUtils.showText(BaseMethod.notNullDefaultValue(json.getMsg(), getString(R.string.string_bind_third_sucess_warn)));
                                qqSwitchCheck(true);
                            } else qqSwitchCheck(false);
                        } else qqSwitchCheck(false);
                    } catch (JSONException e) {
                        qqSwitchCheck(false);
                        e.printStackTrace();
                    }
                } else {
                    qqSwitchCheck(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //绑定微信
    private void bindWx() {
        //微信
        weixinLogin();
    }

    private void weixinLogin() {
        if (isWXAppInstalledAndSupported()) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "none";
            api.sendReq(req);
        } else {
            wxSwitchCheck(false);
            ToastUtils.showText(getString(R.string.string_no_wechat_app_waring));
        }
    }

    //是否安装微信
    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constants.APP_ID);
        return msgApi.isWXAppInstalled();
    }

    //解绑
    private void unbind(String name) {
        showLoadingDialog("");
        PhoneLive.unBiind(getUserToken(), name, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                if (name.equals("wx")) {
                    wxSwitchCheck(true);
                } else {
                    qqSwitchCheck(true);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean json = gson.fromJson(response, GeneralBean.class);
                            if (json != null) {
                                ToastUtils.showText(BaseMethod.notNullDefaultValue(json.getMsg(), getString(R.string.string_unbind_third_sucess_warn)));
                                if (name.equals("wx")) {
                                    wxSwitchCheck(false);
                                } else {
                                    qqSwitchCheck(false);
                                }
                            } else {
                                if (name.equals("wx")) {
                                    wxSwitchCheck(true);
                                } else {
                                    qqSwitchCheck(true);
                                }
                            }
                        } else {
                            if (name.equals("wx")) {
                                wxSwitchCheck(true);
                            } else {
                                qqSwitchCheck(true);
                            }
                        }
                    } catch (JSONException e) {
                        if (name.equals("wx")) {
                            wxSwitchCheck(true);
                        } else {
                            qqSwitchCheck(true);
                        }
                        e.printStackTrace();
                    }
                } else {
                    if (name.equals("wx")) {
                        wxSwitchCheck(true);
                    } else {
                        qqSwitchCheck(true);
                    }
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //发送验证码
    private void getCellPhoneCode(String phone) {
        showLoadingDialog("");
        PhoneLive.getCellPhoneCode(phone, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean generalBean = gson.fromJson(response, GeneralBean.class);
                            ToastUtils.showText(generalBean.getMsg());
                            Intent intent = new Intent(mContext, SettingChangeEmailVerifyPhoneActivity.class);
                            intent.putExtra("phone", phone);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "设置账户安全界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "设置账户安全界面");
    }
}
